//
//  NSObject+Json.m
//  CommonUtility
//
//  Created by liusanchun on 14-8-7.
//  Copyright (c) 2014年 liusanchun. All rights reserved.
//

#import "NSObject+Json.h"
#import <objc/runtime.h>

@implementation NSObject (Json)

/**
 *  将json字符串序列化为NSObject对象
 *
 *  @param json json字符串
 */
- (void)serialization:(NSString*)json
{
    NSDictionary *dataSource = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding]
                                                               options:NSJSONReadingMutableLeaves
                                                                 error:nil];
    [self convert:dataSource];
}

/**
 *  将字典序列化为NSObject对象
 *
 *  @param dictionary 字典
 */
- (void)serializationWithDictionary:(NSMutableDictionary*)dictionary
{
    [self convert:dictionary];
}

- (void)convert:(NSDictionary*)dataSource
{
    
    if([dataSource isKindOfClass:[NSDictionary class]]){
        for (NSString *key in [dataSource allKeys]) {
            if ([[self propertyKeys] containsObject:key]) {
                id propertyValue = [dataSource valueForKey:key];
                if (![propertyValue isKindOfClass:[NSNull class]]
                    && propertyValue != nil) {
                    
                    [self setValue:propertyValue
                            forKey:key];
                }
            } else {
                if ([[self superPropertyKeys] containsObject:key]) {
                    [self setValue:[dataSource valueForKey:key]
                            forKey:key];
                }
                
            }
        }
    }
}

/**
 *  获取父类的属性列表
 *
 *  @return 属性列表
 */
- (NSArray*)superPropertyKeys
{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self superclass], &outCount);
    NSMutableArray *propertys = [NSMutableArray arrayWithCapacity:outCount];
    for (i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f =property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        [propertys addObject:propertyName];
    }
    free(properties);
    return propertys;
}

/**
 *  获取NSObject属性列表
 *
 *  @return 属性列表
 */
- (NSArray*)propertyKeys
{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    NSMutableArray *propertys = [NSMutableArray arrayWithCapacity:outCount];
    for (i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f =property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        [propertys addObject:propertyName];
    }
    free(properties);
    return propertys;
}

@end
